package wymiana.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import wymiana.domain.GroupRequest;
import wymiana.domain.User;

@Repository
public class GroupRequestDao extends GenericDao<GroupRequest> {
	@Autowired
	public GroupRequestDao(SessionFactory sf) {
		super(GroupRequest.class, sf);
	}

	public GroupRequest getGroupRequestById(Integer id) {
		GroupRequest dGroup = (GroupRequest) getById(id);
		return dGroup;
	}

	public List<GroupRequest> getMyRequests(User u) {

		@SuppressWarnings("unchecked")
		List<GroupRequest> gr = getHibernateTemplate()
				.find("select greq from GroupRequest greq  where greq.accepted=false and  greq.dgroup.createUser=?",
						u);
		if (gr != null) {
			for (GroupRequest g : gr) {
				try {
					Hibernate.initialize(g.getAskingUser());
					Hibernate.initialize(g.getDgroup());
				} catch (Exception e) {

				}
			}
			return gr;
		}

		return null;
	}

	public boolean checkIfAdded(GroupRequest r) {

		@SuppressWarnings("unchecked")
		List<GroupRequest> gr = getHibernateTemplate()
				.find("select greq from GroupRequest greq where greq.dgroup=? and greq.askingUser=?",
						r.getDgroup(), r.getAskingUser());
		if (gr != null && !gr.isEmpty()) {
			return true;
		}
		return false;

	}

}
